import { GameConfig } from "../configs/GameConfig"
import { IGrowElement } from "../configs/Grow"
import { Attribute } from "../etc/Attribute"
import { GrowWindow } from "../ui/GrowWindow"
import { PlayerModuleS } from "./PlayerModule"

export class GrowMapping {
    private static mapping: Map<number, IGrowElement[]>

    static getGrowCfgArrayByKind(kind: number):IGrowElement[] {
        this.mappingChecker()
        return this.mapping.get(kind)
    }

    static getGrowFirstCfgByKind(kind: number): IGrowElement{
        return this.getGrowCfgArrayByKind(kind)[0]
    }

    private static mappingChecker() {
        if (this.mapping) return
        this.mapping = new Map()
        for (const cfg of GameConfig.Grow.getAllElement()) {
            if (!this.mapping.has(cfg.Kind)) this.mapping.set(cfg.Kind, [])
            this.mapping.get(cfg.Kind).push(cfg)
        }
    }
}

export class GrowModuleData extends Subdata {
    // value:表ID
    @Decorator.persistence()
    growMap: { [kind: number]: number }

    protected initDefaultData(): void {
        this.growMap = {}
    }
}

export class GrowModuleC extends ModuleC<GrowModuleS, GrowModuleData>{

    protected onStart(): void {
        InputUtil.onKeyDown(Keys.P,()=>{
            UIService.show(GrowWindow)
        })
    }

    requestBuyGrow(kind:number){
        this.server.net_buy_grow_power(kind)
    }
}

export class GrowModuleS extends ModuleS<GrowModuleC, GrowModuleData>{

    net_buy_grow_power(kind: number) {
        let costMoney:number
        let onSuccessNextID:number
        // 第一次购买这种类型的成长属性
        if(!this.currentData.growMap[kind]){
            onSuccessNextID = GrowMapping.getGrowFirstCfgByKind(kind).ID
            costMoney = GrowMapping.getGrowFirstCfgByKind(kind).CostMoney
        }
        else{
            // 当前grow表
            let currentGrowCfg = GameConfig.Grow.getElement(this.currentData.growMap[kind]) 
            // 没有下一个可升级的了
            if(currentGrowCfg.Next == 0) return
            let nextCfg = GameConfig.Grow.getElement(currentGrowCfg.Next)

            onSuccessNextID = nextCfg.ID
            costMoney = nextCfg.CostMoney
        }
        // 金币不足判断
        let playerMD = ModuleService.getModule(PlayerModuleS)
        let have = playerMD.getPlayerAttr(this.currentPlayerId, Attribute.EnumAttributeType.money)
        if(have < costMoney) return
        // 加属性
        this.currentData.growMap[kind] = onSuccessNextID
        // 扣钱
        playerMD.reducePlayerAttr(this.currentPlayerId, Attribute.EnumAttributeType.money, costMoney)
        // 刷新属性
        playerMD.recalculateAllAttribute(this.currentPlayer)
        // 同步
        this.currentData.save(true)
    }
}